<script setup lang="ts">
import { onMounted, ref } from 'vue';
import type { FormInst, FormRules, UploadCustomRequestOptions, UploadFileInfo } from 'naive-ui';
import { useDialog } from 'naive-ui';
import { onBeforeRouteLeave, useRoute } from 'vue-router';
import { useRouterPush } from '@/hooks/common/router';
import {
  deductModuleApplicationCountAction,
  deleteBid,
  getCatalogAction,
  getKnowledgeListAction,
  insertWriteAction,
  msgCheckAction,
  updateWriteAction,
  uploadFileAction
} from '@/service/api';
import { errorMessage, generateRandomCode, successMessage, warningMessage } from '@/utils/utils';
import { useLoading } from '~/packages/hooks';
import { localStg } from '@/utils/storage';
import { USER_INFO } from '@/utils/const';
import {log} from "echarts/types/src/util/log";

const { loading, startLoading, endLoading } = useLoading();
const { routerBack, routerPushByKey } = useRouterPush();

interface FormType {
  projectName: string; // 方案名称
  projectType: number; // 方案类型
  procureUnit: string; // 采购单位
  respondUnit: string; // 应标单位
  knowledge: string; // 引用知识库
}

const formData = ref<FormType>({
  projectName: '',
  projectType: 1,
  procureUnit: '',
  respondUnit: '',
  knowledge: ''
});

const formRef = ref<FormInst | null>(null);

// 校验规则
const rules: FormRules = {
  projectName: {
    required: true,
    message: '请输入项目名称',
    trigger: ['input', 'blur']
  },
  projectType: {
    type: 'number',
    required: true,
    message: '请选择方案类型',
    trigger: 'change'
  },
  procureUnit: {
    required: true,
    message: '请输入采购单位',
    trigger: ['input', 'blur']
  },
  respondUnit: {
    type: 'number',
    required: true,
    message: '请选择应标单位',
    trigger: 'change'
  }
};

// 是否生成中
const isGenerate = ref<boolean>(false);
const showLoading = ref<boolean>(false);
const loadingDes = ref<string>('');
const loadingDesList = ref<string[]>([
  '正在对招标文件进行解析...',
  '招标文件解析中...',
  '招标需求提取中...',
  '投标文件格式读取中...',
  '正在对目录进行重组...',
  '目录生成中...'
]);
const loadingIndex = ref<number>(1);

const { query } = useRoute();

// 剩余次数
const remainTimes = ref<number>(0);

// 行业类型(1.软件类 2.服务类 3.货物类 4.工程类 5.管理 6.设计 7.技术 8.经济类 20.其他)
const typeOptions = ref([
  {
    value: 1,
    label: '软件类'
  },
  {
    value: 2,
    label: '服务类'
  },
  {
    value: 3,
    label: '货物类'
  },
  {
    value: 4,
    label: '工程类'
  },
  {
    value: 5,
    label: '管理类'
  },
  {
    value: 6,
    label: '设计类'
  },
  {
    value: 7,
    label: '技术类'
  },
  {
    value: 8,
    label: '经济类'
  },
  {
    value: 9,
    label: '其他'
  }
]);

const docFilePath = ref<string>('');

const analysisId = ref<number>(Number(query.analysisId));
const analysisFilePath = ref<string>('');
const docFileList = ref<any[]>([]);

onMounted(() => {
  console.log('query: ', query);

  remainTimes.value = Number.parseInt(query.remainTimes as string, 10);

  getKnowledgeListData();

  if (query.docFilePath) {
    analysisFilePath.value = String(query.docFilePath);
    docFilePath.value = analysisFilePath.value;

    const docFileData: UploadFileInfo = {
      id: generateRandomCode(3, 'num'),
      name: docFilePath.value.substring(docFilePath.value.lastIndexOf('/') + 1, docFilePath.value.lastIndexOf('.')),
      status: 'finished',
      url: docFilePath.value
    };
    docFileList.value.push(docFileData);
  }

  console.log('docFileList: ', docFileList.value);
});

const knowledgeList = ref<any[]>([]);
const knowledgeOptions = ref<any[]>([]);

// 获取知识库信息
async function getKnowledgeListData() {
  const params: any = {};
  const { data, error } = await getKnowledgeListAction(params);
  /** folderName: "南京炫佳子公司05" knowledgeName: "120078_15" */
  if (!error) {
    knowledgeList.value = data;
    formData.value.respondUnit = data[0].folderName;
    knowledgeOptions.value = data[0].knowledgeList;
    if (knowledgeOptions.value.length > 0) {
      formData.value.knowledge = knowledgeOptions.value[0].id;
    }
  }
}

// 应标单位变化时
function respondUnitChangeHandle(value: number) {
  knowledgeOptions.value = knowledgeList.value.find(item => item.id === value)?.knowledgeList || [];
  if (knowledgeOptions.value.length > 0) {
    formData.value.knowledge = knowledgeOptions.value[0].id;
  }
}

// 标书文档上传
const customFileRequest = async ({ file, onFinish }: UploadCustomRequestOptions) => {
  if (
    file.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' &&
    file.type !== 'application/msword'
  ) {
    warningMessage('请上传doc格式或docx格式的文档');
    return;
  }

  const formData = new FormData();
  formData.append('uploadFiles', file.file as Blob);
  formData.append('fileType', String(1));

  const { data, error } = await uploadFileAction(formData);
  if (!error) {
    docFilePath.value = data[0].filePath;
    successMessage('上传成功');
    onFinish();
  }
};

// 移除上传的标书文档
function removeFileHandle() {
  docFilePath.value = '';
}

const taskId = ref<number>(0);

const dialog = useDialog();

// 生成目录
async function creatCatalogClick() {
  // await routerPushByKey('document_catalog');
  // return;

  formRef.value?.validate(async errors => {
    if (!errors) {
      if (!docFilePath.value) {
        errorMessage('请上传招标文件');
        return;
      }

      const checkParams: any = {
        moduleValue: localStg.get('moduleId') || 1,
        keyword: `${formData.value.projectName},${formData.value.procureUnit}`
      };

      const { data: checkData, error: checkError } = await msgCheckAction(checkParams);
      if (!checkError) {
        if (checkData && checkData.length > 0) {
          dialog.error({
            title: '温馨提示',
            content: `项目名称或采购单位中包含以下敏感词：\n${checkData.join('，')}`,
            style: 'white-space: pre-line;',
            positiveText: '确认'
          });
          return;
        }
      }

      let respondUnitStr: string = '';
      for (let i: number = 0; i < knowledgeList.value.length; i++) {
        if (knowledgeList.value[i].id === formData.value.respondUnit) {
          respondUnitStr = knowledgeList.value[i].folderName;
          break;
        }
      }

      let projectTypeStr: string = '';
      for (let i: number = 0; i < typeOptions.value.length; i++) {
        if (typeOptions.value[i].value === formData.value.projectType) {
          projectTypeStr = typeOptions.value[i].label;
          break;
        }
      }

      let knowledgeStr: string = '';
      for (let i: number = 0; i < knowledgeOptions.value.length; i++) {
        if (knowledgeOptions.value[i].id === formData.value.knowledge) {
          knowledgeStr = knowledgeOptions.value[i].knowledgeName;
          break;
        }
      }

      const infoPath = [
        `项目名称：${formData.value.projectName}`,
        `方案类型：${projectTypeStr}`,
        `采购单位：${formData.value.procureUnit}`,
        `应标单位：${respondUnitStr}`
      ];

      const insertParams: any = {
        title: formData.value.projectName, // 标题
        type: 1, // 文件类型(1.标书 )
        materialType: 1, // 素材类型(1.标书)
        industryType: formData.value.projectType, // 行业类型(1.软件类 2.服务类 3.货物类 4.工程类 5.管理 6.设计 7.技术 8.经济类 20.其他)
        tenderingUnit: formData.value.procureUnit,
        biddingUnit: respondUnitStr,
        catalogStatus: 0, // 目录生成状态
        originalFilePath: '', // 标书目录文档地址
        filePath: '', // 生成的标书文档地址
        more1: docFilePath.value, // 标书基本信息文档地址
        more2: knowledgeStr
      };
      // 慧眼识标
      if (analysisId.value) {
        insertParams.analysisId = analysisId.value;
      }

      const { data: taskInfo, error: taskError } = await insertWriteAction(insertParams);
      taskId.value = taskInfo.id;
      if (!taskError) {
        // const simpleParams: any = {
        //   tenant_id: '068259_111',
        //   task_id: taskInfo.id,
        //   info_path: infoPath,
        //   zhaobiao_path: docFilePath.value
        // };
        // const { data: simpleInfo, error: simpleError } = await simpleGenerateAction(simpleParams);
        startLoading();
        isGenerate.value = true;
        loadingDes.value = loadingDesList.value[0];
        showLoading.value = true;
        let timer: any = setInterval(() => {
          loadingDes.value = loadingDesList.value[loadingIndex.value];
          if (loadingIndex.value === loadingDesList.value.length - 1) {
            loadingIndex.value = loadingDesList.value.length - 1;
          } else {
            loadingIndex.value += 1;
          }
        }, 30000);
        const getParams: any = {
          task_id: taskInfo.id,
          zhaobiao_path: docFilePath.value
        };
        const { data: simpleInfo, error: simpleError } = await getCatalogAction(getParams);
        console.log('招标信息：', simpleInfo);
        showLoading.value = false;
        isGenerate.value = false;
        // 清理定时器
        if (timer) {
          clearInterval(timer);
          timer = null;
        }
        endLoading();
        if (!simpleError) {
          const userInfo = localStg.get(USER_INFO);
          const deductParams: any = {
            moduleId: localStg.get('moduleId') || 1,
            usedContent: 1,
            applicationId: 1,
            contentDesc: formData.value.projectName,
            tenantId: userInfo!.user.tenantId,
            createBy: userInfo!.user.userId
          };
          const { data: deductInfo, error: deductError } = await deductModuleApplicationCountAction(deductParams);
          if (!deductError) {
            // 信息更新
            const params: any = {
              id: taskInfo.id,
              title: formData.value.projectName, // 标题
              type: 1, // 文件类型(1.标书 )
              materialType: 1, // 素材类型(1.标书)
              industryType: formData.value.projectType, // 行业类型(1.软件类 2.服务类 3.货物类 4.工程类 5.管理 6.设计 7.技术 8.经济类 20.其他)
              tenderingUnit: formData.value.procureUnit,
              biddingUnit: respondUnitStr,
              catalogStatus: 1, // 目录生成状态
              originalFilePath: simpleInfo.doc_path, // 标书目录文档地址
              filePath: '', // 生成的标书文档地址
              more1: docFilePath.value // 标书基本信息文档地址
            };
            await updateWriteAction(params);

            const pushParams: any = {
              generateType: 0,
              taskId: taskInfo.id,
              fileName: formData.value.projectName,
              infoPath: infoPath.join(','),
              zhaoBiaoPath: docFilePath.value,
              catalogPath: simpleInfo.doc_path,
              isOneClickWrite: 1
            };
            await routerPushByKey('document_catalog', { query: pushParams });
          }
        }
      }
    }
  });
}

onBeforeRouteLeave((to, from, next) => {
  console.log('loading: ', isGenerate.value);
  if (isGenerate.value) {
    dialog.warning({
      title: '温馨提示',
      content: `注意：当前标书目录正在生成中，请问是否确认放弃本次标书生成？`,
      positiveText: '确认放弃',
      negativeText: '取消',
      onPositiveClick: () => {
        // 终止目录生成任务并且删除对应任务记录
        deleteTaskRecordHandle();
        next(); // 阻止离开
      },
      onNegativeClick: () => {
        next(false);
      }
    });
  } else {
    next(); // 阻止离开
  }
});

// 删除任务记录
async function deleteTaskRecordHandle() {
  await deleteBid(taskId.value);
}
</script>

<template>
  <NLayout class="h-full" :native-scrollbar="false">
    <NSpace vertical class="h-full">
      <NSpin :show="showLoading" :rotate="false" size="large">
        <template #icon>
          <img src="@/assets/imgs/spin-loading.gif" alt="" width="240" height="240" />
        </template>
        <template #description>
          <div class="des-box">
            <div class="des-title">小主，为保证质量，您的内容生成需要等待2-5分钟</div>
            <div class="des-text">{{ loadingDes }}</div>
          </div>
        </template>
        <div class="content-box">
          <NCard class="card-content w-full" header-style="margin-top: 20px;" content-style="padding: 0 416px;">
            <template #header>
              <NText class="ml-416px font-size-30px font-bold" style="fontfamily: HarmonyOS Sans SC">
                根据招标要求编写
              </NText>
            </template>
            <NForm
              ref="formRef"
              :model="formData"
              :rules="rules"
              size="large"
              require-mark-placement="left"
              label-placement="left"
              label-width="120"
            >
              <NFormItem
                label="项目名称"
                label-style="font-size: 20px; font-family: HarmonyOS Sans SC;"
                path="projectName"
              >
                <NInput
                  v-model:value="formData.projectName"
                  :maxlength="50"
                  placeholder="请按照“xxx项目”的格式输入方案名称"
                />
              </NFormItem>
              <NFormItem
                label="方案类型"
                label-style="font-size: 20px; font-family: HarmonyOS Sans SC;"
                path="projectType"
              >
                <NRadioGroup v-model:value="formData.projectType" name="radiogroup">
                  <NSpace>
                    <NRadio v-for="item in typeOptions" :key="item.label" :value="item.value">
                      {{ item.label }}
                    </NRadio>
                  </NSpace>
                </NRadioGroup>
              </NFormItem>
              <NFormItem
                label="采购单位"
                label-style="font-size: 20px; font-family: HarmonyOS Sans SC;"
                path="procureUnit"
              >
                <NInput v-model:value="formData.procureUnit" :maxlength="60" />
              </NFormItem>
              <NFormItem
                label="应标单位"
                label-style="font-size: 20px; font-family: HarmonyOS Sans SC;"
                path="respondUnit"
              >
                <NSelect
                  v-model:value="formData.respondUnit"
                  :options="knowledgeList"
                  label-field="folderName"
                  value-field="id"
                  @update:value="respondUnitChangeHandle"
                />
              </NFormItem>
              <NFormItem label="引用知识库" label-style="font-size: 20px; font-family: HarmonyOS Sans SC;">
                <NSelect
                  v-model:value="formData.knowledge"
                  :options="knowledgeOptions"
                  label-field="folderName"
                  value-field="id"
                />
              </NFormItem>
              <NFormItem
                class="upload-form-item"
                label="招标文件"
                label-style="font-size: 20px; font-family: HarmonyOS Sans SC;"
                required
              >
                <div class="upload-tag">（请上传招标文档或磋商文档，最大字符数12w）</div>
                <div class="upload-box">
                  <NUpload
                    directory-dnd
                    :max="1"
                    accept=".doc, .docx"
                    :default-file-list="docFileList"
                    :show-remove-button="!analysisFilePath"
                    :custom-request="customFileRequest"
                    @remove="removeFileHandle"
                  >
                    <NUploadDragger>
                      <div class="mb-12px mt-20px w-full flex-y-center justify-center">
                        <img src="@/assets/bid-materials/folder.png" alt="" width="52" height="44" />
                      </div>
                      <NText style="font-size: 16px">点击或将文件拖拽到这里上传</NText>
                      <NP depth="3" style="margin: 8px 0 0 0">支持扩展名：.doc、.docx</NP>
                    </NUploadDragger>
                  </NUpload>
                </div>
              </NFormItem>
            </NForm>
            <template #footer>
              <NSpace vertical align="center">
                <NButton class="create-button" :bordered="false" :loading="loading" @click="creatCatalogClick">
                  生成目录
                </NButton>
                <span class="create-tips">(点击生成目录 将会消耗撰写次数1次。剩余次数为：{{ remainTimes }}次)</span>
              </NSpace>
            </template>
          </NCard>
        </div>
      </NSpin>
    </NSpace>
  </NLayout>
</template>

<style scoped lang="scss">
.bg-layout {
  padding: 16px 16px 0 !important;
  background: url('@/assets/imgs/edit-bg.png');
  background-size: 100% 100%;
}
.content-box {
  background: rgba(229, 231, 253, 0.6);
  border-radius: 12px;
  border: 1px solid #faf9fd;
  padding: 33px 31px 0px 31px;
  margin: 17px 15px 0;
}
.card-content {
  background: url('@/assets/imgs/create-bg.png') no-repeat;
  background-size: 100% 100%;
  padding-bottom: 40px;
}
.upload-box {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  width: 100%;
  justify-content: space-between;
}
.des-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 10px;
  .des-title {
    font-size: 20px;
    font-weight: 400;
    line-height: 24px;
  }
  .des-text {
    margin-top: 15px;
    font-size: 18px;
    font-weight: 400;
    line-height: 24px;
    opacity: 0.6;
  }
}
:deep(.n-spin) {
  width: auto;
  height: auto;
}
.upload-form-item {
  position: relative;
}
.upload-tag {
  position: absolute;
  top: 50px;
  left: -110px;
  width: 96px;
  font-weight: bold;
  font-size: 16px;
  color: #4501b7;
  line-height: 24px;
}
.create-button {
  margin-top: 20px;
  border-radius: 8px;
  font-weight: 400;
  font-size: 24px;
  color: #ffffff;
  line-height: 24px;
  width: 475px;
  height: 72px;
  background: linear-gradient(90deg, #e877ae 0%, #7c73f3 100%);
}
.create-button:hover {
  background: linear-gradient(90deg, #e877ae 0%, #7c73f3 100%);
  color: #ffffff;
}
.create-tips {
  font-weight: 400;
  font-size: 20px;
  color: #ff6e6e;
  line-height: 24px;
}
</style>
